#!/bin/bash

# shellcheck disable=SC1091

set -o errexit
set -o nounset
set -o pipefail
# set -o xtrace # Uncomment this line for debugging purpose

# Load libraries
. /libmariadb.sh
. /libos.sh

# Load MariaDB environment variables
eval "$(mysql_env)"

# 备份配置
BACKUP_SCHEDULE="${BACKUP_SCHEDULE:-58 3 * * *}"  # 默认每天凌晨3:58执行备份
BACKUP_RETENTION="${BACKUP_RETENTION:-7}"         # 默认保留7份备份
BAK_USER="${BAK_USER:-root}"
BAK_PWD="${BAK_PWD:-}"
BACKUP_ENABLE="${BACKUP_ENABLE:-false}"            # 新增：默认关闭备份

# 创建备份脚本
cat > /backup/backup.sh << 'EOF'
#!/bin/bash
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/bitnami/mariadb/${TIMESTAMP}"
ARCHIVE_FILE="/bitnami/mariadb/${TIMESTAMP}.tar.gz"

# 执行备份
mariabackup --backup --target-dir="${BACKUP_DIR}" --user="${BAK_USER}" --password="${BAK_PWD}"

# 打包压缩备份文件夹
tar -czf "${ARCHIVE_FILE}" -C /bitnami/mariadb "${TIMESTAMP}"

# 删除原始备份文件夹（可选）
rm -rf "${BACKUP_DIR}"

# 删除旧的压缩备份，只保留最新的N份
cd /bitnami/mariadb
ls -t | grep -E '^[0-9]{8}_[0-9]{6}\.tar\.gz$' | tail -n +$((BACKUP_RETENTION + 1)) | xargs -r rm -f
EOF

# 确保备份脚本可执行
chmod +x /backup/backup.sh

# 根据 BACKUP_ENABLE 判断是否执行定时任务
if [ "$BACKUP_ENABLE" = "true" ]; then
    echo "备份已启用，开始调度任务..."
    nohup ./cron.sh "${BACKUP_SCHEDULE} /backup/backup.sh" > /backup/log.txt 2>&1 &
    echo "定时备份任务已启动，日志输出到 log.txt"
else
    echo "备份未启用 (BACKUP_ENABLE=false)，跳过调度任务。"
fi

flags=("--defaults-file=${DB_CONF_DIR}/my.cnf" "--basedir=$DB_BASE_DIR" "--datadir=$DB_DATA_DIR" "--socket=${DB_TMP_DIR}/mysql.sock" "--port=$DB_PORT_NUMBER")
[[ -z "${DB_EXTRA_FLAGS:-}" ]] || flags=("${flags[@]}" "${DB_EXTRA_FLAGS[@]}")

info "** Starting MariaDB **"
if am_i_root; then
    exec gosu "$DB_DAEMON_USER" "${DB_SBIN_DIR}/mysqld" "${flags[@]}"
else
    exec "${DB_SBIN_DIR}/mysqld" "${flags[@]}"
fi
